<template>
  <el-dialog v-model="__reactive.visible"
             :title="!__reactive.dataForm.id ? t('add') : t('update')"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             :closed="resetDataForm">
    <el-form v-loading="__reactive.loading"
             :model="__reactive.dataForm"
             ref="dataFormRef"
             @keyup.enter="submitDataFormHandle()"
             label-width="180px">
      <el-form-item prop="username" :label="t('customer.username')">
        <el-input v-model="__reactive.dataForm.username" :placeholder="t('customer.username')"></el-input>
      </el-form-item>
      <el-form-item prop="password" :label="t('customer.password')">
        <el-input v-model="__reactive.dataForm.password" :placeholder="t('customer.password')"></el-input>
      </el-form-item>
      <el-form-item prop="realName" :label="t('customer.realName')">
        <el-input v-model="__reactive.dataForm.realName" :placeholder="t('customer.realName')"></el-input>
      </el-form-item>
      <el-form-item prop="headUrl" :label="t('customer.headUrl')">
        <el-input :readonly="true" :disabled="true" v-model="__reactive.dataForm.headUrl" :placeholder="t('customer.headUrl')"></el-input>
      </el-form-item>
      <el-form-item prop="gender" :label="t('customer.gender')">
        <el-input v-model="__reactive.dataForm.gender" :placeholder="t('customer.gender')"></el-input>
      </el-form-item>
      <el-form-item prop="email" :label="t('customer.email')">
        <el-input v-model="__reactive.dataForm.email" :placeholder="t('customer.email')"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" :label="t('customer.mobile')">
        <el-input v-model="__reactive.dataForm.mobile" :placeholder="t('customer.mobile')"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="__reactive.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
  import { ref, reactive, computed, nextTick, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import http from '@/utils/http'
  import _ from 'lodash'
  import { ElForm, ElMessage, UploadUserFile } from 'element-plus'
  import { uploadImgEcho } from '@/utils'
  import useUserStore from '@/store/user'

  const userStore = useUserStore()

  const { t } = useI18n()

  const emit = defineEmits(['refreshPageHandle'])

  const uploadRef = ref()

  const __reactive = reactive({
    visible: false,
    previewVisible: false,
    loading: false,
    uploadUrl: `${window.SITE_CONFIG.apiURL}/shop/customer/upload/`,
    fileList: [] as UploadUserFile[],
    fileObj: {},
    previewImgUrl: '',
    uploadImageLoading: false,
    dataForm: {
      id: '',
      username: '',
      password: '',
      realName: '',
      headUrl: '',
      gender: 2, // 性别   0：男   1：女    2：保密
      email: '',
      mobile: ''
    }
  }) as any

  /**
   * Life Cycle
   */
  async function init() {
    __reactive.visible = true
    resetDataForm()
    await nextTick()
    __reactive.dataForm.shopId = userStore.$state.id
    if (__reactive.dataForm.id) {
      getInfo()
    }
  }

  /**
   * Dialog
   */
  const dialogId = ref(0)

  watch([() => dialogId.value], (val1) => {
    __reactive.dataForm.id = val1[0]
  })

  /**
   * Data Form
   */
  const dataFormRef = ref<InstanceType<typeof ElForm>>() as any

  const resetDataForm = () => {
    dataFormRef.value?.resetFields()
    uploadRef.value?.clearFiles()
    __reactive.fileList = []
    __reactive.fileObj = {}
    __reactive.previewImgUrl = ''
  }

  const submitDataFormHandle = _.debounce(
    () => {
      dataFormRef.value?.validate(async (valid) => {
        if (!valid) {
          return false
        }
        __reactive.loading = true
        const res = await http[!__reactive.dataForm.id ? 'post' : 'put'](
          '/shop/customer',
          __reactive.dataForm,
          { headers: { 'content-type': 'application/x-www-form-urlencoded' } }
        )
        __reactive.loading = false
        if (res.code !== 0) {
          return ElMessage.error(res.msg)
        }
        ElMessage({
          message: t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            __reactive.visible = false
            emit('refreshPageHandle')
          }
        })
      })
    },
    1000,
    { leading: true, trailing: false }
  )

  /**
   * Get Info
   */
  const getInfo = async () => {
    __reactive.loading = true
    const res = await http.get(`/shop/customer/get/${__reactive.dataForm.id}`)
    __reactive.loading = false
    if (res.code !== 0) {
      return ElMessage.error(res.msg)
    }
    __reactive.dataForm = _.pick(res.data, ['id', 'username', 'password', 'realName', 'headUrl', 'gender', 'email', 'mobilex'])
    // uploadImgEcho(__reactive.dataForm.productImg, uploadRef.value)
  }

  defineExpose({
    init,
    dialogId
  })
</script>
